//
//  AddMarketWatchViewController.m
//  bondwatch_purecode
//
//  Created by Jason Yuan on 5/29/15.
//  Copyright (c) 2015 Sumridge. All rights reserved.
//

#import "AddMarketWatchViewController.h"

@interface AddMarketWatchViewController ()
{
    UITextField *listNameField;
    UIButton *createWatchButton;
}

@end

@implementation AddMarketWatchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"Add List";
    
    UIBarButtonItem *settingBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Settings"] style:UIBarButtonItemStylePlain target:self action:@selector(settingBarButtonPressed:)];
    settingBarButton.tintColor = SUMRIDGECOLOR;
    
    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Back"] style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonPressed:)];
    backBarButton.tintColor = SUMRIDGECOLOR;
    
    NSArray *leftBarButtonArray = @[settingBarButton, backBarButton];
    
    self.navigationItem.leftBarButtonItems = leftBarButtonArray;
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    listNameField = [[UITextField alloc] init];
    listNameField.borderStyle = UITextBorderStyleRoundedRect;
    listNameField.layer.borderColor = SUMRIDGECOLOR.CGColor;
    [self.view addSubview:listNameField];
    
    [listNameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(74);
        make.left.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
    }];
    
    createWatchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [createWatchButton setBackgroundColor:SUMRIDGECOLOR];
    createWatchButton.layer.cornerRadius = 5.0f;
    [createWatchButton setTitle:@"Create List" forState:UIControlStateNormal];
    [createWatchButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [createWatchButton addTarget:self action:@selector(createList:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:createWatchButton];
    
    [createWatchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(114);
        make.left.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.height.mas_equalTo(34);
    }];
}

- (void)createList:(id)sender {
    if ([listNameField.text isEqualToString:@""]) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"Please enter a listName";
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            // Do something...
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [listNameField becomeFirstResponder];
        });
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
    NSDictionary *params = @{@"watchListName":listNameField.text};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager GET:CREATELISTURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        DDLogVerbose(@"CreateList result: %@", result);
        NSDictionary *dictionary = [result objectFromJSONString];
        NSNumber *success = [dictionary objectForKey:@"success"];
        if ([success intValue] == 1) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = [NSString stringWithFormat:@"Create Group(%@) successfully.", listNameField.text] ;
            
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                // Do something...
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
            
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = [NSString stringWithFormat:@"Create Group(%@) failure.", listNameField.text] ;
            hud.detailsLabelText = @"Please try again";
            
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                // Do something...
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            });
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        DDLogError(@"createList error:\n%@", error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void)settingBarButtonPressed:(id)sender {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (void)backBarButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
